<html>
<head>

<title>Groovy Goodness: Getting Information About Objects</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Getting Information About Objects</h3>

<div class="post">
<p>To get some information about an object we often use the <code>toString()</code> method in Java. In Groovy we can use the same <code>toString()</code> method, but we have two more alternatives. We can use the <code>dump()</code> method on an object and we get information about the name of the object, the hashcode and the values of the fields. And we can use the <code>inspect()</code> method, which will try to return a String which matches closest what we would type in Groovy code to create the object.</p>
<pre class="brush:groovy">
def map = [username: 'mrhaki']
assert '[&quot;username&quot;:&quot;mrhaki&quot;]' == map.inspect()

def list = [1, 2, 3, 'Groovy']
assert '[1, 2, 3, &quot;Groovy&quot;]' == list.inspect()

def range = 0..10
assert '0..10' == range.inspect()

def str = 'Inspecting object with Groovy'
assert '&quot;Inspecting object with Groovy&quot;' == str.inspect()

def dom = groovy.xml.DOMBuilder.newInstance().parseText('&lt;root&gt;&lt;language&gt;Groovy&lt;/language&gt;&lt;/root&gt;')
println dom.documentElement.inspect()
// Output:
// &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
// &lt;root&gt;
//   &lt;language&gt;Groovy&lt;/language&gt;
// &lt;/root&gt;</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>